//
//  UserAccount.swift
//  我的微博
//
//  Created by gongjunna on 15/7/31.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

class UserAccount: NSObject ,NSCoding {
    
    var access_token : String?
    var expires : NSTimeInterval = 0.0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires)
        }
    }
    var uid : String?
    
    var expiresDate : NSDate?
    
    var name : String?
    
    var avatar_large : String?
    
    static private   var userAccount : UserAccount?
    //定义一个  useerAccount 来记录  所有的用户数据
    init(dictData  :[String : AnyObject]) {
       super.init()
        
        setValuesForKeysWithDictionary(dictData)
        UserAccount.userAccount = self
        loadUserInfo()
        
    }

    class func loadUserAccounts() ->  UserAccount? {
    
        if userAccount == nil {
        
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        }
        
        
        if  userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
        
            userAccount = nil
        }
        
        return userAccount
    }

    // 定义  沙盒路径
    static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    
    func loadUserInfo() {
 
        NetWorkTools.shardNetWorkTool.loadUserInfo { (result, error) -> () in
            // 设置用户信息
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            // 保存用户信息
            self.saveAccount()
        }
    
    }

// 保存用户信息
    
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile:UserAccount.accountPath)
    
    }
  override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
  func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(access_token, forKey: "access_token")
    aCoder.encodeDouble(expires, forKey: "expires")
    aCoder.encodeObject(uid, forKey: "uid")
}

     required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires = aDecoder.decodeDoubleForKey("expires") as Double
        uid = aDecoder.decodeObjectForKey("uid") as? String
        
    }
}
